﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using log4net;

namespace Klinkby.MicroBus.Service
{
    [RunInstaller(true)]
    public class MicroBusServiceInstaller : Installer
    {
        internal const string ServiceName = "microbus";
        readonly ILog _log = LogManager.GetLogger(typeof(MicroBusServiceInstaller));
        readonly ServiceProcessInstaller serviceProcessInstaller1 = new ServiceProcessInstaller();
        readonly ServiceInstaller serviceInstaller1 = new ServiceInstaller();

        public MicroBusServiceInstaller()
        {
            _log.Debug(".ctor");
            // serviceProcessInstaller1 
            // 
            this.serviceProcessInstaller1.Account = ServiceAccount.NetworkService;
            // 
            // serviceInstaller1 
            // 
            this.serviceInstaller1.ServiceName = ServiceName;
            this.serviceInstaller1.DisplayName = "Klinkby MicroBus";
            this.serviceInstaller1.Description = "Tiny Enterprise Service Bus";
            this.serviceInstaller1.StartType = ServiceStartMode.Automatic;

            // 
            // ProjectInstaller 
            // 
            Installers.AddRange(
                new System.Configuration.Install.Installer[] 
                { 
                    this.serviceProcessInstaller1, 
                    this.serviceInstaller1
                }
                );
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _log.Debug("Dispose");
                serviceProcessInstaller1.Dispose();
                serviceInstaller1.Dispose();
            }
            base.Dispose(disposing);
        }

        protected override void OnBeforeUninstall(System.Collections.IDictionary savedState)
        {
            base.OnBeforeUninstall(savedState);
            try
            {
                using (ServiceController ctrl = new ServiceController(ServiceName))
                {
                    _log.Info("Stopping service");
                    ctrl.Stop(); // stop the service
                }
            }
            catch
            {}
        }

        protected override void OnAfterInstall(System.Collections.IDictionary savedState)
        {
            base.OnAfterInstall(savedState);
            try
            {
                using (ServiceController ctrl = new ServiceController(ServiceName))
                {
                    _log.Info("Starting service");
                    ctrl.Start(); // start the service
                }
            }
            catch
            { }
        }
    }
}
